package com.wanxing.main;

import android.app.ActionBar;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.zhny.wxginger.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements OnClickListener,
        OnPageChangeListener {
    private View mActionBarView;
    private TextView title;
    private ViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;
    private List<String> tagList = new ArrayList<String>();
    private List<ChangeColorIconWithText> mTabIndicators = new ArrayList<ChangeColorIconWithText>();
    private ActionBar actionBar;
    private android.app.FragmentManager fm = getFragmentManager();

    private long exitTime = 0;

    public static SharedPreferences preferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cusActionBar(); // 自定义actionbar

        initView(); // 動畫
        initDatas(title.getText().toString()); // important
        mViewPager.setAdapter(mAdapter); // add fragment to viewpaper ....
        initEvent();


    }

    // overflow点击事件,改变fragment
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.isCheckable()) {
            item.setChecked(true);
        }
        int position;
        switch (item.getItemId())
        {
            case R.id.no_043:
                title.setText("生姜大棚1号");
                actionBar.setTitle("043");
                break;
            case R.id.no_044:
                title.setText("生姜大棚2号");
                actionBar.setTitle("044");
                break;

//            case R.id.no_01:
//                title.setText("1号大棚");
//                actionBar.setTitle("001");
//                break;
//            case R.id.no_02:
//                title.setText("2号大棚");
//                actionBar.setTitle("002");
//                break;
//            case R.id.no_06:
//                title.setText("6号大棚");
//                actionBar.setTitle("006");
//                break;
            default:
                // return super.onOptionsItemSelected(mi);
                break;
        }
        position = mViewPager.getCurrentItem();
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(position);
        return true;
    }

    public void cusActionBar()
    {// 自定义actionbar
        actionBar = getActionBar();
        actionBar.setDisplayShowHomeEnabled(false); // 图标不显示
        setOverflowButtonAlways();
        mActionBarView = LayoutInflater.from(this).inflate(
                R.layout.actionbar_layout, null);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        title = (TextView) mActionBarView.findViewById(R.id.title);

        title.setText("生姜大田1号");
        actionBar.setCustomView(mActionBarView, lp);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setTitle("043");
    }

    /**
     *
     */
    private void initEvent() {

        mViewPager.setOnPageChangeListener(this);

    }

    private void initDatas(String str) {
        DataShowFragment dataShowFragment = new DataShowFragment();
//        DataAnalyzeFragment dataAnalyzeFragment = new DataAnalyzeFragment();
        ControlFragmentNew controlFragment = new ControlFragmentNew();
        SetorFragment setorFragment = new SetorFragment();
        mTabs.add(dataShowFragment);
//        mTabs.add(dataAnalyzeFragment);
        mTabs.add(controlFragment);
        mTabs.add(setorFragment);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mTabs.get(position);
            }

            @Override
            public void startUpdate(ViewGroup container) {  //更新容器viewpaper
                super.startUpdate(container);

            }

            @Override
            public void finishUpdate(ViewGroup container) {
                super.finishUpdate(container);
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }

            @Override
            public int getItemPosition(Object object) {
                return super.getItemPosition(object);
            }

            @Override
            public long getItemId(int position) {
                return super.getItemId(position);
            }


        };

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.main, menu);
            menu.add(0, R.id.no_043, 0, "043");
            menu.add(0, R.id.no_044, 0, "044");
        return true;
    }

    private void setOverflowButtonAlways() // 显示overflow
    {
        try {
            ViewConfiguration config = ViewConfiguration.get(this); // view配置
            // configuration
            Field menuKey = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKey.setAccessible(true);
            menuKey.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

        ChangeColorIconWithText one = (ChangeColorIconWithText) findViewById(R.id.id_indicator_one);
        mTabIndicators.add(one);
//        ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
//        mTabIndicators.add(two);
        ChangeColorIconWithText two = (ChangeColorIconWithText) findViewById(R.id.id_indicator_two);
        mTabIndicators.add(two);
        ChangeColorIconWithText three = (ChangeColorIconWithText) findViewById(R.id.id_indicator_three);
        mTabIndicators.add(three);

        one.setOnClickListener(this);
//        two.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);

        one.setIconAlpha(1.0f);

    }

    /**
     * 改變menu的icon
     */
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {

        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public void onClick(View v) {
        clickTab(v);

    }

    /**
     * 設置Tab
     *
     * @param v
     */
    private void clickTab(View v) {
        resetOtherTabs();

        switch (v.getId()) {
            case R.id.id_indicator_one:
                mTabIndicators.get(0).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(0, false);
                break;

            case R.id.id_indicator_two:
                mTabIndicators.get(1).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.id_indicator_three:
                mTabIndicators.get(2).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(2, false);
                break;
        }
    }

    /**
     * 閲嶇疆鍏朵粬鐨凾abIndicator鐨勯鑹
     */
    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicators.size(); i++) {
            mTabIndicators.get(i).setIconAlpha(0);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        // Log.e("TAG", "position = " + position + " ,positionOffset =  "
        // + positionOffset);
        if (positionOffset > 0) {
            ChangeColorIconWithText left = mTabIndicators.get(position);
            ChangeColorIconWithText right = mTabIndicators.get(position + 1);
            left.setIconAlpha(1 - positionOffset);
            right.setIconAlpha(positionOffset);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(MainActivity.this, "再点一次就让你退出去", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPageSelected(int position) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // TODO Auto-generated method stub

    }

}
